using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
using DevComponents.AdvTree;
using System.IO;
using DevComponents.DotNetBar;
using Toolkit.Library;
using WDTVHubGen.LoggingService;
using Shell32;

namespace WDTVHubGen
{
    public partial class frmHubGenMain : DevComponents.DotNetBar.Office2007RibbonForm
    {
        private Node rootNode = null;
        private Options options = new Options();
        private ElementStyle _RightAlignFileSizeStyle = null;
        Shell32.Shell shell = new Shell32.Shell();
        
        


        public frmHubGenMain()
        {
            InitializeComponent();
        }

        private void btnOpenDirectory_Click(object sender, EventArgs e)
        {
            //add the directory to the tree control
            //iterate through the directories and add files
            // folderBrowserDialog1.SelectedPath = cboPath.Text;

            string selectedPath = null;
            _RightAlignFileSizeStyle = new ElementStyle();
            _RightAlignFileSizeStyle.TextAlignment = DevComponents.DotNetBar.eStyleTextAlignment.Far;


            if (folderBrowserDialog1.ShowDialog() != DialogResult.Cancel)
            {
                selectedPath = folderBrowserDialog1.SelectedPath;
                rootNode = new Node(selectedPath);
                LoadDirectories(rootNode, new DirectoryInfo(selectedPath));
                // LoadDirectories(selectedPath, rootNode);
                //cboPath.Text = folderBrowserDialog1.SelectedPath;
                treeVideoList.Nodes.Add(rootNode);
                treeVideoList.ExpandAll();

            }
        }

        private void LoadDirectories(string directoryPath, Node parent)
        {
            string[] filelist;
            List<string> validExtensions = Util.Utilities.GetValidExtensions(options.ValidExtensions);

            filelist = Directory.GetFiles(directoryPath, "*.*",
                                          (options.RecursiveSearch)
                                              ? SearchOption.AllDirectories
                                              : SearchOption.TopDirectoryOnly);

            foreach (string filename in filelist)
            {

                if (validExtensions.Contains(Path.GetExtension(filename).ToLower()))
                {
                    //Node newnode = new Node(Path.GetFileName(filename));
                    Node node = new Node();
                    node.Text = Path.GetFileName(filename);
                    node.Image = global::WDTVHubGen.Properties.Resources.film_smaller;
                    node.Cells.Add(new Cell("File"));
                    Cell cell = new Cell(filename.Length.ToString("N0"));
                    cell.StyleNormal = _RightAlignFileSizeStyle;
                    node.Cells.Add(cell);

                    parent.Nodes.Add(node);
                }
            }
        }

        private void LoadDirectories(Node parent, DirectoryInfo directoryInfo)
        {
            DirectoryInfo[] directories = directoryInfo.GetDirectories();
            foreach (DirectoryInfo dir in directories)
            {
                if ((dir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) continue;
                Node node = new Node();
                node.Tag = dir;
                node.Text = dir.Name;
                node.Image = global::WDTVHubGen.Properties.Resources.FolderClosed;
                node.ImageExpanded = global::WDTVHubGen.Properties.Resources.FolderOpen;
                node.Cells.Add(new Cell("Local Folder"));
                node.Cells.Add(new Cell());
                node.ExpandVisibility = eNodeExpandVisibility.Visible;
                parent.Nodes.Add(node);

                GetFilesFromDirectory(node, dir);
            }
            GetFilesFromDirectory(parent, directoryInfo);


        }

        private void GetFilesFromDirectory(Node parent, DirectoryInfo directoryInfo)
        {
            List<string> validExtensions = Util.Utilities.GetValidExtensions(options.ValidExtensions);
            Shell32.Folder objFolder = shell.NameSpace(directoryInfo.FullName);
            FileInfo[] files = directoryInfo.GetFiles();
            foreach (FileInfo file in files)
            {
                if (validExtensions.Contains(Path.GetExtension(file.Name).ToLower()))
                {
                    parent.Nodes.Add(AddFileDetails(file, objFolder));
                }
            }
        }

        Dictionary<int, KeyValuePair<string, string>> GetFileProps(string filename)
        {
            Shell shell = new Shell();
            Folder fldr = shell.NameSpace(Path.GetDirectoryName(filename));
            FolderItem itm = fldr.ParseName(Path.GetFileName(filename));
            Dictionary<int, KeyValuePair<string, string>> fileProps = new Dictionary<int, KeyValuePair<string, string>>();
            for (int i = 0; i < 255; i++)
            {
                string propValue = fldr.GetDetailsOf(itm, i);
                if (propValue != "")
                {
                    fileProps.Add(i, new KeyValuePair<string, string>(fldr.GetDetailsOf(null, i), propValue));
                }
            }
            return fileProps;
        }

        private Node AddFileDetails(FileInfo file, Folder fld)
        {
            Node node = new Node();
            node.Text = file.Name;
            FolderItem itm = fld.ParseName(file.Name);
            Image newImage = GetImageFromFileName(file.FullName);
            if (newImage == null) node.Image = global::WDTVHubGen.Properties.Resources.film_smaller;
            else node.Image = newImage;
            //node.Image = global::TreeControl.Properties.Resources.Document;
            node.Cells.Add(new Cell("File"));
            Cell cell = new Cell(file.Length.ToString("N0"));
            cell.StyleNormal = _RightAlignFileSizeStyle;
            Cell cellwidth = new Cell(fld.GetDetailsOf(itm, 285));
            Cell cellheight = new Cell(fld.GetDetailsOf(itm, 283));
            
            node.Cells.Add(cell);
            node.Cells.Add(cellwidth);
            node.Cells.Add(cellheight);
            return node;
        }

        private void GetFileDetails(string fullname)
        {
            List<string> arrHeaders = new List<string>();

            Shell32.Shell shell = new Shell32.Shell();
            Shell32.Folder objFolder = shell.NameSpace(Path.GetDirectoryName(fullname));

            for (int i = 0; i < short.MaxValue; i++)
            {
                string header = objFolder.GetDetailsOf(null, i);
                if (String.IsNullOrEmpty(header))
                    break;
                arrHeaders.Add(header);
            }

            foreach (Shell32.FolderItem2 item in objFolder.Items())
            {
                for (int i = 0; i < arrHeaders.Count; i++)
                {
                    Console.WriteLine("{0}\t{1}: {2}", i, arrHeaders[i], objFolder.GetDetailsOf(item, i));
                }
            }


        }

        private Image GetImageFromFileName(string filename)
        {
            Image newImage = null;
            string imagefilename = Path.ChangeExtension(filename, ".jpg");
            if (File.Exists(imagefilename))
                newImage = resizeImageForTreeFromFilename(imagefilename, new Size(32,32));
            else
            {
                imagefilename = Path.Combine(Path.GetDirectoryName(imagefilename), "." + Path.GetFileName(imagefilename));
                if (File.Exists(imagefilename)) newImage = resizeImageForTreeFromFilename(imagefilename, new Size(32,32));
            }
            return newImage;
        }

        private Image resizeImageForTreeFromFilename(string filename,Size size)
        {
            Image imgToResize = Image.FromFile(filename);
        if (options.VerboseErrors == Options.LoggingLevels.verbose) CLogger.WriteLog(ELogLevel.DEBUG, "In resizeImage");
        int sourceWidth = imgToResize.Width;
        int sourceHeight = imgToResize.Height;

        float nPercentW = (size.Width/(float) sourceWidth);
        float nPercentH = (size.Height/(float) sourceHeight);

        float nPercent = nPercentH < nPercentW ? nPercentH : nPercentW;

        var destWidth = (int) (sourceWidth*nPercent);
        var destHeight = (int) (sourceHeight*nPercent); 
        var b = new Bitmap(destWidth,destHeight); 
        Graphics g = Graphics.FromImage(b);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);

        g.Dispose();

        return b;
    }
    } 
}